package org.jingouzhui.domain.strategy.model.entity;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.jingouzhui.types.common.Delimiter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @description: 策略规则实体
 * @author: jingouzhui
 * @date: 2025/4/25 11:47
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class StrategyRuleEntity {

    /**
     * 抽奖策略ID
     */
    private Long strategyId;

    /**
     * 抽奖奖品ID【规则类型为策略，则不需要奖品ID】
     */
    private Integer awardId;

    /**
     * 抽象规则类型；1-策略规则、2-奖品规则
     */
    private Integer ruleType;

    /**
     * 抽奖规则类型【rule_random - 随机值计算、rule_lock - 抽奖几次后解锁、rule_luck_award - 幸运奖(兜底奖品)】
     */
    private String ruleModel;

    /**
     * 抽奖规则比值
     */
    private String ruleValue;

    /**
     * 抽奖规则描述
     */
    private String ruleDesc;


    /**
     * 获取rule_model为rule_weight时rule_value中每一种情况可以抽取的awardList
     * 数据案例：rule_weight 10:102,103 70:106,107 1000:104,105
     * @return map
     */
    public Map<String, List<Integer>> getRuleWeightValues() {
        if (!"rule_weight".equals(this.getRuleModel())) {
            return null;
        }
        Map<String, List<Integer>> awardMap = new HashMap<>();
        String ruleValue = this.getRuleValue();
        if (ruleValue == null) {
            return awardMap;
        }
        String[] rule = ruleValue.split(Delimiter.SPACE);
        for (String s : rule) {
            String[] parts = s.split(Delimiter.COLON);
            if (parts.length != 2) {
                throw  new IllegalArgumentException("Invalid rule weight: " + s);
            }
            String awardValue = parts[1];
            String[] valueList = awardValue.split(Delimiter.COMMA);
            List<Integer> collect = Stream.of(valueList)
                    .filter(Objects::nonNull)
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
            awardMap.put(s,collect);
        }
        return awardMap;
    }
}
